package com.xiaoshuidi.cloud.module.member.xxljob;

import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.module.member.framework.sms.SmsCodeProperties;
import com.xiaoshuidi.cloud.module.member.mapper.MemberOmnipotentPasswordMapper;
import com.xiaoshuidi.cloud.module.member.pojo.user.MemberOmnipotentPassword;
import com.xiaoshuidi.cloud.module.member.util.CustomDateUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;

import static cn.hutool.core.util.RandomUtil.randomInt;


@Slf4j
@Component
@RequiredArgsConstructor
public class MemberLoginPasswordChangeJob {
    @Value("${login_organization}")
    private String organization;

    private final MemberOmnipotentPasswordMapper memberOmnipotentPasswordMapper;

    private final SmsCodeProperties smsCodeProperties;

    @TenantIgnore
    @XxlJob("member-login-password-change-job")
    @Transactional
    public void execute() {
        log.info("member-login-password-change-job更改万能密码Job Start" + LocalDate.now());
        //查询万能密码数据
        MemberOmnipotentPassword passwordDo = memberOmnipotentPasswordMapper.getByOrganization(organization);
        //返回true，如果过期就重新生成新的密码
        if (CustomDateUtil.checkEffective(passwordDo.getEffectiveDate())) {
            //重新生成密码
            String code = String.valueOf(randomInt(smsCodeProperties.getBeginCode(), smsCodeProperties.getEndCode() + 1));

            memberOmnipotentPasswordMapper.updatePassword(MemberOmnipotentPassword.builder()
                    .password(code)
                    .effectiveDate(passwordDo.getEffectiveDate().plusMonths(1))
                    .id(passwordDo.getId())
                    .build());
        }

    }

}
